package com.example.service;

import com.alibaba.fastjson.JSON;
import com.example.pojo.Book;
import com.example.pojo.Content;
import com.example.util.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public Boolean createBulkDoc(String keyword) throws IOException {
//		根据ID获取到book 并且封装为一个对象
//		new QueryWrapper<Book>().ge( "id", 1)
        HtmlParseUtil htmlParseUtil = new HtmlParseUtil();
        List<Content> goodsList = htmlParseUtil.getGoodsList(keyword);

        BulkRequest bulkRequest = new BulkRequest();
//		将多个request封装到一起
        for (Content good : goodsList) {
            IndexRequest createDocRequest = new IndexRequest("jd_goods");
            //		将对象转换为json数据
            String bookJson = JSON.toJSONString(good);
            createDocRequest.source(bookJson, XContentType.JSON);
            bulkRequest.add(createDocRequest);
        }
        try {
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<Map<String, Object>> searchPage(String keyword, Integer pageNo, Integer pageSize) {
        SearchRequest request = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        sourceBuilder.query(QueryBuilders.termQuery("title", keyword));

        sourceBuilder.from(pageNo);//分页的起始位置
        sourceBuilder.size(pageSize);//每页的条数

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);
        request.source(sourceBuilder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            ArrayList<Map<String ,Object>> arrayList = new ArrayList<>();
            for (SearchHit hit : hits) {
//				和上面的一样 同样是getSourceAsString
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField title = highlightFields.get("title");//获取高亮的字段
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();//原来的结果
                if(title!=null){
                    Text[] fragments = title.fragments();
                    StringBuilder name = new StringBuilder();
                    for (Text fragment : fragments) {
                        name.append(fragment);
                    }
                    sourceAsMap.put("title", name.toString());//高亮字段替换掉原来的字段
                }
                arrayList.add(sourceAsMap);
            }
            return arrayList;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
